package com.map;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Locale;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.google.android.maps.GeoPoint;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class GetDirectionbyText extends Activity {

	private String str_start_point;
	private String str_end_point;
	private TextView text_direction;
	private TextView text_direction_detail;
	private ImageButton getText_Direction;
	private String value;
	private String value2;
	private EditText end_point;
	private EditText start_point;
	private Runnable getXml;
	private Handler handler;
	private String start_address;
	private String end_address;
	private String totalTime;
	private String totalDistance;
	private String instructions[];
	private int size;
	private String myLan;
	private String myLong;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.direction_by_text);

		start_point = (EditText) findViewById(R.id.edit_start_text);
		end_point = (EditText) findViewById(R.id.edit_end_text);
		text_direction = (TextView) findViewById(R.id.text_direction);
		text_direction_detail = (TextView) findViewById(R.id.text_direction_detail);
		getText_Direction = (ImageButton) findViewById(R.id.bt_getdirection_text);
		
		myLan = getIntent().getStringExtra("MYLAN");
		myLong = getIntent().getStringExtra("MYLONG");
		
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if (value.equals("OK")) {
					text_direction
							.setText("- Điểm bắt đầu: "
									+ start_address
									+ "\n"
									+ "- Điểm đến: "
									+ end_address
									+ "\n"
									+ "- Thời gian: "
									+ totalTime
									+ "\n"
									+ "- Khoảng cách: "
									+ totalDistance
									+ "\n"
									+ "- - - - - - - - - - - - - - - - - - - - - -  - - -");

					text_direction_detail.setText(printString(instructions));
				} else {
					text_direction.setText(value2);
					text_direction_detail.setText("");
				}

			}

		};
		
		//thực hiện lấy dữ liệu trong luồng
		getXml = new Runnable() {

			public void run() {
				// TODO Auto-generated method stub

				StringBuilder urlString = new StringBuilder();
				urlString
						.append("http://maps.googleapis.com/maps/api/directions/xml?origin=");
				urlString.append(str_start_point);
				urlString.append("&destination=");
				urlString.append(str_end_point);
				urlString.append("&sensor=false");
				urlString.append("&language=vi");

				Document doc = null;
				HttpURLConnection urlConnection = null;
				URL url = null;
				DocumentBuilderFactory dbf = null;
				DocumentBuilder db = null;

				try {
					url = new URL(urlString.toString());
					urlConnection = (HttpURLConnection) url.openConnection();
					int res = urlConnection.getResponseCode();
					if (res == HttpURLConnection.HTTP_OK) {
						dbf = DocumentBuilderFactory.newInstance();
						db = dbf.newDocumentBuilder();
						doc = db.parse(urlConnection.getInputStream());
						//xử lí dữ liệu lấy từ google
						Element elementOfDoc = doc.getDocumentElement();
						//lấy nội dung của thẻ <status>
						NodeList nodelist = elementOfDoc
								.getElementsByTagName("status");
						value = nodelist.item(0).getFirstChild().getNodeValue();
						if (value.equals("OK")) {				
							NodeList node_StartAddress = elementOfDoc
									.getElementsByTagName("start_address");
							start_address = node_StartAddress.item(0)
									.getFirstChild().getNodeValue();							
							NodeList node_EndAddress = elementOfDoc
									.getElementsByTagName("end_address");
							end_address = node_EndAddress.item(0)
									.getFirstChild().getNodeValue();
							NodeList node_Duration = elementOfDoc
									.getElementsByTagName("duration");
							int sizeOfDuration = node_Duration.getLength();
							Element node_Duration_item = (Element) node_Duration
									.item(sizeOfDuration - 1);
							Element node_Duration_text = (Element) node_Duration_item
									.getElementsByTagName("text").item(0);
							totalTime = node_Duration_text.getFirstChild()
									.getNodeValue();
							NodeList node_Distance = elementOfDoc
									.getElementsByTagName("distance");
							int sizeOfDistance = node_Distance.getLength();
							Element node_Distance_item = (Element) node_Distance
									.item(sizeOfDistance - 1);
							Element node_Ditance_text = (Element) node_Distance_item
									.getElementsByTagName("text").item(0);
							totalDistance = node_Ditance_text.getFirstChild()
									.getNodeValue();

							NodeList node_Step = elementOfDoc
									.getElementsByTagName("step");
							getDataOfStepNode(node_Step);

						} else {
							value2 = "Đã xảy ra lỗi(" + value + ")" + "\n"
									+ "Hãy nhập đúng địa chỉ!";
						}

					}
				} catch (MalformedURLException e) {
					Log.d("xxxxx", "MalformedURLException:");
					e.printStackTrace();
				} catch (IOException e) {
					Log.d("xxxxx", "IOException:");
					e.printStackTrace();
				} catch (ParserConfigurationException e) {
					Log.d("xxxxx", "ParserConfigurationException:");
					e.printStackTrace();
				} catch (SAXException e) {
					Log.d("xxxxx", "SAXException:");
					e.printStackTrace();
				}

				Message msg = handler.obtainMessage();
				handler.sendMessage(msg);
			}
		};
		
		//bắt sự kiện nhấn button
		getText_Direction.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				str_start_point = start_point.getText().toString();
				str_end_point = end_point.getText().toString();

				if(str_start_point.equalsIgnoreCase("Từ đây")){
					str_start_point = myLan + "," + myLong;
				}
							
					Thread connect = new Thread(getXml);
					connect.start();			
			}
		});

	}

	//lấy dữ liệu của thẻ <Step>
	private void getDataOfStepNode(NodeList nodelist) {
		size = nodelist.getLength();
		instructions = new String[size];
		for (int i = 0; i < size; i++) {
			Element node = (Element) nodelist.item(i);
			Element instructionsNode = (Element) node.getElementsByTagName(
					"html_instructions").item(0);
			instructions[i] = i + 1 + "."
					+ getStringOfHtmlInstructions(instructionsNode) + "\n";
		}

	}

	//xử lí xâu trong thẻ <html_instructions>
	private String getStringOfHtmlInstructions(Element iNode) {

		String str = iNode.getTextContent();

		String str1[] = str.split("<b>");
		str = printString2(str1);
		String strs2[] = str.split("</b>");
		str = printString2(strs2);
		String str3[] = str.split("<div style=\"font-size:0.9em\">");
		str = printString2(str3);
		String str4[] = str.split("</div>");
		str = printString2(str4);

		return str;

	}

	private String printString(String[] s) {
		String str = "";
		for (int i = 0; i < s.length; i++) {
			str = str + s[i] + "\n";
		}
		return str;
	}

	private String printString2(String[] s) {
		String str = "";
		for (int i = 0; i < s.length; i++) {
			str = str + s[i];
		}
		return str;
	}


	// chuyen doi ten sang geopoint
	private GeoPoint convertName(String str_point) {
		GeoPoint point = null;
		Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
		try {
			List<Address> addresses = geoCoder
					.getFromLocationName(str_point, 5);
			if (addresses.size() > 0) {
				point = new GeoPoint(
						(int) (addresses.get(0).getLatitude() * 1000000.0),
						(int) (addresses.get(0).getLongitude() * 1000000.0));
			} else {
				Toast.makeText(
						getApplicationContext(),
						"Địa điểm bạn nhập không chính xác!\n"
								+ "Vui lòng nhập lại.", Toast.LENGTH_LONG)
						.show();
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return point;

	}
	
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}

}
